<template>
  <!-- 课程推荐列表组件 -->
  <div>
    <!-- 标题栏 -->
    <div class="section-header">
      <!-- 标题区域 -->
      <div class="section-title">
        <span class="title-icon"></span>
        <h2>课程推荐</h2>
      </div>
      <!-- 更多课程链接 -->
      <div class="more-link" @click="seeMoreCourses"><i class="el-icon-arrow-right"></i></div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="fetchRecommendedCourses" class="retry-button">重试</button>
    </div>
    
    <!-- 课程列表 -->
    <div v-else class="course-list">
      <div 
        v-for="course in displayedCourses" 
        :key="course.courseId" 
        class="course-card"
        @click="goToCourseDetail(course.courseId)"
      >
        <!-- 课程封面图 -->
        <div class="course-image" :style="{ backgroundImage: 'url(' + getImageUrl(course) + ')' }">
          <div class="course-tag" v-if="course.recommendWeight >= 3">热门</div>
        </div>
        <!-- 课程信息 -->
        <div class="course-info">
          <h3 class="course-title" :title="course.title">{{ course.title }}</h3>
          <div class="course-meta">
            <span class="course-school">分类: {{ getCategoryName(course.categoryId) }}</span>
          </div>
          <div class="course-stats">
            <div class="stat">
              <i class="el-icon-user"></i>
              <span class="study-people">学习人数: {{ course.studyPeople || '暂无数据' }}</span>
            </div>
          </div>
          <div class="course-price" :class="{'free': course.price === 0}">
            {{ course.price === 0 ? '免费' : '¥' + course.price.toFixed(2) }}
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="!loading && !error && displayedCourses.length === 0" class="empty-container">
      <p>暂无推荐课程</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { getUserRecommendations, getHotRecommendations } from '@/api/course'
import { useRouter } from 'vue-router'

/**
 * 课程推荐列表组件
 * 展示用户推荐或热门推荐课程，支持分类筛选和课程详情跳转
 */
export default {
  name: 'RecommendedCourseList',
  
  setup() {
    // 状态管理
    const courses = ref([])                // 课程列表数据
    const loading = ref(true)              // 加载状态
    const error = ref('')                  // 错误信息
    const allCourses = ref([])             // 所有课程数据
    const router = useRouter()             // 路由实例
    
    /**
     * 显示所有课程
     * @returns {Array} 课程列表
     */
    const displayedCourses = computed(() => {
      return courses.value;
    });
    
    /**
     * 获取课程图片URL
     * @param {Object} course - 课程对象
     * @returns {string} 图片URL
     */
    const getImageUrl = (course) => {
      return course.titleImg || 'https://via.placeholder.com/300x150?text=无图片';
    };
    
    /**
     * 获取推荐课程数据
     */
    const fetchRecommendedCourses = async () => {
      loading.value = true;
      error.value = '';
      
      try {
        // 先尝试获取用户个性化推荐
        const userRecommendationsResponse = await getUserRecommendations();
        
        if (userRecommendationsResponse.code === 200 && userRecommendationsResponse.data && userRecommendationsResponse.data.length > 0) {
          // 如果有用户推荐数据，使用用户推荐
          processCourseData(userRecommendationsResponse.data);
        } else {
          // 如果没有用户推荐数据，获取热门推荐
          const hotRecommendationsResponse = await getHotRecommendations();
          if (hotRecommendationsResponse.code === 200 && hotRecommendationsResponse.data) {
            processCourseData(hotRecommendationsResponse.data);
          } else {
            throw new Error('没有找到推荐课程');
          }
        }
      } catch (err) {
        error.value = '获取推荐课程失败，请重试';
        loading.value = false;
      }
    };
    
    /**
     * 处理课程数据
     * @param {Array} data - 课程数据数组
     */
    const processCourseData = (data) => {
      // 确保所有课程数据都有基本属性
      const validCourses = data.map(course => {
        // 确保推荐权重有值，默认为0
        if (course.recommendWeight === undefined || course.recommendWeight === null) {
          course.recommendWeight = 0;
        }
        // 确保学习人数有值，默认为0
        if (course.studyPeople === undefined || course.studyPeople === null) {
          course.studyPeople = 0;
        }
        return course;
      });
      
      // 按照推荐权重降序排序，确保优先展示权重高的课程
      const sortedCourses = validCourses.sort((a, b) => {
        return b.recommendWeight - a.recommendWeight;
      });
      
      // 取前8个课程显示
      const topCourses = sortedCourses.slice(0, 8);
      
      if (topCourses.length > 0) {
        // 先将所有课程保存起来
        allCourses.value = topCourses;
        courses.value = topCourses;
      } else {
        error.value = '暂无推荐课程';
      }
      
      loading.value = false;
    };
    
    /**
     * 跳转到课程详情页面
     * @param {string|number} courseId - 课程ID
     */
    const goToCourseDetail = (courseId) => {
      // 确保courseId是字符串类型
      const courseIdStr = String(courseId)
      
      // 使用try-catch防止导航错误
      try {
        router.push({
          name: 'CourseDetail',
          params: { id: courseIdStr }
        }).then(() => {
          // 导航完成后延迟100ms刷新页面
          setTimeout(() => {
            window.location.reload()
          }, 1)
        })
      } catch (err) {
        error.value = '跳转到课程详情页面失败';
      }
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchRecommendedCourses();
    });
    
    // 获取分类名称
    const getCategoryName = (categoryId) => {
      const categories = {
        1: '学术',
        2: '技术与工程',
        3: '商业与管理',
        4: '艺术与设计',
        5: '职业技能',
        6: '健康与医学',
        7: '语言与文化',
        8: '科技与未来趋势',
        9: '体育与健身'
      }
      return categories[categoryId] || '其他'
    }
    
    return {
      courses,
      loading,
      error,
      allCourses,
      router,
      displayedCourses,
      getImageUrl,
      fetchRecommendedCourses,
      goToCourseDetail,
      getCategoryName
    };
  }
};
</script>

<style scoped>
/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1c86ee;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误状态 */
.error-container {
  text-align: center;
  padding: 30px 0;
  color: #ff4d4f;
}

.retry-button {
  background-color: #1c86ee;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  margin-top: 10px;
  cursor: pointer;
}

.retry-button:hover {
  background-color: #1976d2;
}

/* 课程列表 */
.course-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.course-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
  cursor: pointer;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.course-image {
  height: 160px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.course-tag {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 2px 8px;
  background-color: #ff6b6b;
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.course-info {
  padding: 15px;
}

.course-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.course-school {
  color: #666;
  font-size: 14px;
}

.course-teacher {
  color: #999;
  font-size: 13px;
}

.study-people {
  color: #999;
  font-size: 13px;
}

.course-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.stat {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.stat i {
  margin-right: 5px;
  font-size: 14px;
}

.course-price {
  font-size: 16px;
  font-weight: 500;
  color: #ff6b6b;
}

.course-price.free {
  color: #52c41a;
}

/* 空状态 */
.empty-container {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .course-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 992px) {
  .course-list {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .section-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
}

@media (max-width: 576px) {
  .course-list {
    grid-template-columns: 1fr;
  }
}

.title-icon {
  width: 4px;
  height: 18px;
  background-color: #1890ff;
  margin-right: 8px;
  border-radius: 2px;
}
</style> 